package com.zh.common.base

import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.NonNull
import androidx.annotation.Nullable
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ScreenUtils
import com.zh.common.R
import com.zh.common.ktx.viewBinding
import com.zh.common.utils.JumpActivity
import com.zh.common.view.dialog.LoadingDialog
import java.lang.reflect.ParameterizedType


abstract class BaseDialogFragment<VB : ViewBinding> : DialogFragment(), JumpActivity,
    DialogInterface.OnDismissListener {

    private val TAG = "BaseDialogFragment"
    lateinit var viewBinding: VB
    private var rootView: View? = null
    lateinit var mContext: Context
    private var loadingDialog: LoadingDialog? = null

    open val isBottomInto = false // 默认中间弹出
    open val dialogHeight = 0 // 高度
    abstract fun initView(savedInstanceState: Bundle?, view: View)

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
        dialog?.setOnDismissListener(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.StyleDialog)
    }

    override fun onCreateView(
        @NonNull inflater: LayoutInflater, @Nullable container: ViewGroup?,
        @Nullable savedInstanceState: Bundle?
    ): View? {
        ARouter.getInstance().inject(this)
        if (null == rootView) { //如果缓存中有rootView则直接使用
            this.rootView = viewBinding<VB>(inflater, container).root
        } else {
            rootView!!.parent?.let { it2 -> (it2 as ViewGroup).removeView(rootView) }
        }
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //在OnCreate方法中调用下面方法，然后再使用线程，就能在uncaughtException方法中捕获到异常
        initView(savedInstanceState, view)
        dialog?.apply { setDialogAnimation() }
    }

    override fun onPause() {
        super.onPause()
        onDestroyView()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //为rootView做缓存，在viewpager中使用fragment时可以提升切换流畅度
        rootView?.let {
            it.parent?.let { it2 -> (it2 as ViewGroup).removeView(it) }
        }
        dialog?.dismiss()
    }

    //外部点击消失
    fun isCanceledOnTouchOutside(isOutside: Boolean = true) {
        dialog?.setCanceledOnTouchOutside(isOutside)
    }

    //弹出动画 - 默认中间弹出
    private fun setDialogAnimation() {
        dialog?.window?.let {
            if (isBottomInto) {
                it.setLayout(
                    ScreenUtils.getScreenWidth(),
                    if (dialogHeight > 0) dialogHeight else ViewGroup.LayoutParams.WRAP_CONTENT
                )
                it.setGravity(Gravity.BOTTOM)
                it.setWindowAnimations(android.R.style.Animation_InputMethod)
            } else {
                it.setLayout(
                    ScreenUtils.getScreenWidth() * 4 / 5,
                    if (dialogHeight > 0) dialogHeight else ViewGroup.LayoutParams.WRAP_CONTENT
                )
                it.setGravity(Gravity.CENTER)
                it.setWindowAnimations(android.R.style.Animation_Dialog)
            }
        }
    }

    fun show(manager: FragmentManager) {
        show(manager, "dialog")
    }

    override fun show(manager: FragmentManager, tag: String?) {
        try {
            //防止连续点击add多个fragment
            manager.beginTransaction().remove(this).commit()
            super.show(manager, tag)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun getLoadingDialog() {
        loadingDialog ?: also { loadingDialog = LoadingDialog(mContext) }
    }

    /**
     * 显示加载dialog
     */
    fun showLoading() {
        try {
            getLoadingDialog();loadingDialog?.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 结束dialog
     */
    fun dismissLoading() {
        try {
            loadingDialog?.let { if (it.isShowing) it.dismiss() }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        if (KeyboardUtils.isSoftInputVisible(requireActivity())) {
            KeyboardUtils.toggleSoftInput()
        }
    }
}